<template>
  <div class="app-content displayFlexC">
    <div class="Tinymce_box">
      <div style="margin-bottom: 1%;box-shadow: 5px 5px 10px#eee;padding: 10px 20px" class="displayFlexR">
            <div class="fl">
                <vxe-button class="bigBtn" @click="submit" icon="el-icon-s-promotion">发布</vxe-button>
            </div>
            <vxe-form
            title-colon
            ref="xForm"
            title-align="right"
            title-width="120"
            :data="formData"
            :rules="formRules">
            <vxe-form-item title="文章标题" field="title" span="24" :item-render="{}" title-overflow="title">
                <template #default="params">
                    <vxe-input v-model="params.data.title" placeholder="请输入文章标题" clearable @input="$refs.xForm.updateStatus(params)"></vxe-input>
                </template>
            </vxe-form-item>
            <vxe-form-item title="文章关键字" field="keyword" span="24" :item-render="{}" title-overflow="title">
                <template #default="params">
                    <vxe-input v-model="params.data.keyword" placeholder="请输入文章关键字" clearable @input="$refs.xForm.updateStatus(params)"></vxe-input>
                </template>
            </vxe-form-item>
            <vxe-form-item title="新闻板块" field="type" span="24" :item-render="{}" title-overflow="title">
                <template #default="params">
                    <vxe-select v-model="params.data.type" placeholder="选择产品类别">
                          <vxe-option v-for="item in NewsTemplate" :key="item.name" :value="item.id" :label="item.name"></vxe-option>
                      </vxe-select>
                </template>
            </vxe-form-item>
                        
            <vxe-form-item title="文章简介" field="synopsis" span="24" :item-render="{}" title-overflow="title">
                <template #default="params">
                    <!-- <vxe-textarea v-model="params.data.c" placeholder="请输入文章简介" :autosize="{minRows: 3, maxRows: 10}" clearable @input="$refs.xForm.updateStatus(params)" style="height:auto;"></vxe-textarea> -->
                    <el-input type="textarea" v-model="params.data.synopsis" placeholder="请输入文章简介" clearable @input="$refs.xForm.updateStatus(params)"></el-input>
                </template>
            </vxe-form-item>
            </vxe-form>
            <div class="fl">
                <vxe-button class="bigBtn" @click="save_draft">保存</vxe-button>
            </div>
      </div>
      <div class="top">
        <div id="edit" style="z-index: 1"></div>
        <div v-if="content" class="editor-content">
          <h3>预览效果：</h3>
          <div v-html="content" />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import E from 'wangeditor'
import $ from 'jquery'
import { getNewsTemplate,putDraftNumInfo } from '@/api/newsAndNotice'
import { imageUpload, releaseSubmit } from '@/api/editor'
export default {
  data() {
    return {
      // 表单
      formData: {
          title: '',
          keyword: '',
          synopsis: '',
          type: '',
          img: null
        },
        formRules: {
            title: [
                { required: true, message: '请输入文章标题' },
            ],
            keyword: [
                { required: true, message: '请输入文章关键字' }
            ],
            synopsis: [
                { required: true, message: '请输入文章简介' }
            ],
            type: [
                { required: true, message: '请选择板块名称' }
            ]
        },
      content: '',
      imgList: '',
      releaseData: {},
      // 新闻板块
      NewsTemplate: null,
      uid: null,
      //编辑
      rowData: null,
    }
  },
  watch: {
    content(val, oldVal) {
        console.log('this.content', this.content)
    }
  },
  mounted() {
    this.rowData = this.$route.query.data
    if(this.rowData != null){
      this.formData = this.rowData
      this.content = this.rowData['text']
    }
    this.initEditor()
    this.initNew()
    this.getUserInfo()
  },
  methods: {
    // 获取用户信息
    getUserInfo(){
      this.$store.dispatch('user/getInfo').then(res => {
        console.log('user info', res)
        this.uid = res.user.id
      })
    },
    initEditor() {
      const editor = new E('#edit')
      // 隐藏上传网络图片
      editor.config.showLinkImg = false
      editor.config.customUploadImg = (resultFiles, insertImgFn) => {
        var formData = new FormData()
        // 上传图片，返回结果，将图片插入到编辑器中
        for (let i = 0; i < resultFiles.length; i++) {
          formData.append('file', resultFiles[i])
        }
        console.log(formData.get('file'), 'formData.file')
        imageUpload(formData).then((res) => {
          console.log(res)
          if (res.resp_code === 0) {
            this.imgList = res.data
            // 将图片上传到编辑器
            for (let i = 0; i < res.data.length; i++) {
              insertImgFn(res.data[i])
            }
          }
        })
      }
      // 配置 onchange 回调函数
      editor.config.onchange = (newHtml) => {
        this.content = editor.txt.html()
      }
      editor.create()
      if(this.rowData != null){
        editor.txt.html(this.rowData['text'])
      }
      
      $('.w-e-text-container').css({"height": "90%"})
    },
    async submit() {
        const $form = this.$refs.xForm
        const errMap = await $form.validate().catch(errMap => errMap)
        if (errMap) {
            // this.$XModal.message({ status: 'error', message: '校验不通过！' })
        } else {
            // this.$XModal.message({ status: 'success', message: '校验成功！' })
            this.$confirm('是否发布？', '', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.releaseData = this.formData
                this.releaseData['img'] = this.imgList[0]
                this.releaseData['uid'] = this.uid
                this.releaseData['text'] = this.content
                // 发布--待审核
                this.releaseData['status'] = 1
                this.releaseData['issueStatus'] = 1
                releaseSubmit(this.releaseData).then(res => {
                  console.log('发布成功', res)
                  this.imgList = ''
                  this.releaseData ={}
                  this.$message({ message: '发布成功！', type: 'success' })
                  this.$router.push('/news/Notice_push/Notice_push_index')
                })
            })
        }
    },
    // 保存未草稿
    async save_draft(){
      const $form = this.$refs.xForm
        const errMap = await $form.validate().catch(errMap => errMap)
        if (errMap) {
            // this.$XModal.message({ status: 'error', message: '校验不通过！' })
        } else {
          this.$confirm('是否保存为草稿？', '', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.releaseData = this.formData
            this.releaseData['img'] = this.imgList[0]
            this.releaseData['uid'] = this.uid
            this.releaseData['text'] = this.content
            // 发布--待审核
            this.releaseData['status'] = 1
            this.releaseData['issueStatus'] = 0
            if(this.rowData != null){
              // 修改
              putDraftNumInfo(this.releaseData).then(res => {
                console.log('保存成功', res)
                this.imgList = ''
                this.releaseData ={}
                this.$message({ message: '保存成功！', type: 'success' })
                this.$router.push({path: '/news/Notice_push/Notice_push_draft'})
              })
            }else{
              //新增
              releaseSubmit(this.releaseData).then(res => {
                console.log('保存成功', res)
                this.$message({ message: '保存成功！', type: 'success' })
                this.$router.push({path: '/news/Notice_push/Notice_push_draft'})
              })
            }
            
          })
        }
    },
    initNew(){
        getNewsTemplate(1).then(res => {
            console.log('公告板块 res', res)
            this.NewsTemplate = res.data.records
        })
    },
  }
}
</script>
<style lang="scss" scoped>
@import '../../../styles/all';
::v-deep.vxe-form .vxe-form--item:nth-of-type(1), ::v-deep.vxe-form .vxe-form--item:nth-of-type(2), ::v-deep.vxe-form .vxe-form--item:nth-of-type(3){
    width: 20%;
}
.app-content {
  flex: 1;
  padding: 20px;
  background-color: #f0f2f5;
  .Tinymce_box {
    flex: 1;
    height: 100%;
    background-color: white;
    padding: 24px;
    border-radius: 2px;
    display: flex;
    flex-direction: column;
    .vxe-form{
        flex: 1;
    }
    .top {
      flex: 1;
      display: flex;
      .editor-content {
        overflow: auto;
        margin-left: 30px;
        flex-grow: 1;
        border: 2px dashed #f1f1f1;
        padding: 0 20px;
        h3 {
          color: #808080;
        }
      }
    }
  }
  
}
</style>